<?php
declare (strict_types=1);

namespace app\common\model;

class Menu extends Base
{
    protected $table = 'auth_rule';

    protected function children(): object
    {
        return $this->hasMany(Menu::class, 'pid')
            ->field('id,name,title,sub_title,pid,status,sort,css')
            ->order('sort asc')->with('children');
    }

    protected function getHrefAttr($value, $data): string
    {
        return $data['name'] && $data['name'] != '#' ?
            (strstr($data['name'], '/') ? url($data['name'])->build() : url($data['name'] . '/index')->build()) : $data['name'];
    }

    public static function getNewMenu($pid = 1, $rules = ''): array
    {
        try {
            $that = parent::where(['pid' => $pid, 'status' => 1])
                ->field('id,name,pid,title,sub_title,css')
                ->order('sort asc')->append(['href']);
            if ($rules) {
                $that->whereIn('id', $rules);
            }
            $list = $that->select();
            foreach ($list as &$item) {
                $item->child = self::getNewMenu($item->id, $rules);
            }

            return $list->toArray();
        } catch (\Exception $e) {

            return [];
        }
    }

    public function getAuth($id): array
    {
        try {
            $rule = Role::where(['id' => $id])->value('rules');
            $menu = $this->getNewMenu();

            return ['menu' => $menu, 'rule' => $rule ? explode(',', $rule) : []];
        } catch (\Exception $e) {

            return [];
        }
    }

    public static function getNavigation($name, $param = '', $type = 1): array
    {
        if ($param) {
            $name .= '?' . http_build_query($param);
        }
        $s_nav = parent::where(['name' => $name, 'type' => $type])->field('id,pid,title')->find();
        $p_nav = '';
        if ($s_nav) {
            $p_nav = parent::where(['id' => $s_nav['pid']])->value('title');
        }

        return [
            's_nav' => $s_nav ? $s_nav['title'] : '未知',
            'p_nav' => $p_nav ?: '未知',
            'id' => $s_nav ? $s_nav->id : ''
        ];
    }
}